import numpy as np
import skfuzzy as fuzz
from django.shortcuts import render, redirect
from asgiref.sync import sync_to_async
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from skfuzzy import control as ctrl

# 1. 污泥隶属度计算
def Sludge(a):
    sludge = [0, 0, 0]  # 默认隶属度为0，依次对应SD,MD,LD
    if a < 0 or a > 100:
        return (print("输入值有误"))
    elif 0 <= a <= 50:
        sludge[0] = (50 - a) / 50
        sludge[1] = a / 50
    elif 50 < a <= 100:
        sludge[1] = (100 - a) / 50    #  40/50
        sludge[2] = (a - 50) / 50      # 10/50
    return sludge

# 2. 油脂隶属度计算
def Grease(a):
    grease = [0, 0, 0]  # 默认隶属度为0,依次对应NG,MG,LG
    if a < 0 or a > 100:
        return (print("输入值有误"))
    elif 0 <= a <= 50:
        grease[0] = (50 - a) / 50
        grease[1] = a / 50
    elif 50 < a <= 100:
        grease[1] = (100 - a) / 50   #  30/50
        grease[2] = (a - 50) / 50   #  10/50
    return grease

# 3. 规则前提推理，并运算取最小值
def Rules(a, b):  # a为污泥隶属度，b为油脂隶属度
    rules_value = [0, 0, 0, 0, 0, 0, 0, 0, 0]  # 依次对应9条规则结果VS,M,L,S,M,L,M,L,VL
    if a[0] != 0 and b[0] != 0:
        rules_value[0] = min(a[0], b[0])  # 返回规则下最小值
    if a[0] != 0 and b[1] != 0:
        rules_value[1] = min(a[0], b[1])
    if a[0] != 0 and b[2] != 0:
        rules_value[2] = min(a[0], b[2])
    if a[1] != 0 and b[0] != 0:
        rules_value[3] = min(a[1], b[0])
    if a[1] != 0 and b[1] != 0:
        rules_value[4] = min(a[1], b[1])
    if a[1] != 0 and b[2] != 0:
        rules_value[5] = min(a[1], b[2])
    if a[2] != 0 and b[0] != 0:
        rules_value[6] = min(a[2], b[0])
    if a[2] != 0 and b[1] != 0:
        rules_value[7] = min(a[2], b[1])
    if a[2] != 0 and b[2] != 0:
        rules_value[8] = min(a[2], b[2])
    return rules_value

# 4. 每条规则推理输出
def Inference(a):  # a为9条规则下的结果隶属度
    time_level = [0, 0, 0, 0, 0]  # 默认时间隶属值为0，依次对应VS,S,M,L,VL
    time_level[0] = a[0]    # 0
    time_level[1] = a[3]    # 0
    if (a[1] != 0 or a[4] != 0 or a[6] != 0):  # 去零值然后取剩下的最小值
        list_1 = [a[1], a[4], a[6]]
        for i in range(len(list_1) - 1, -1, -1):
            if list_1[i] == 0:
                list_1.remove(0)
        time_level[2] = min(list_1)
    if (a[2] != 0 or a[5] != 0 or a[7] != 0):
        list_2 = [a[2], a[5], a[7]]
        for i in range(len(list_2) - 1, -1, -1):
            if list_2[i] == 0:
                list_2.remove(0)
        time_level[3] = min(list_2)
    time_level[4] = a[8]
    return time_level

# 5. 由加权平均判决法可得，根据洗涤时间隶属函数的反函数用相应的隶属度求出时间论域中对应的值
def Max_membership(a):  # a为时间隶属度
    time = [0, 0, 0, 0, 0, 0, 0, 0]  # 时间隶属函数八个区间分别对应的时间值
    time[0] = 30 - 30 * a[0]
    time[1] = 30 * a[1]
    time[2] = 60 - 30 * a[1]
    time[3] = 30 * a[2] + 30
    time[4] = 90 - 30 * a[2]
    time[5] = 30 * a[3] + 60
    time[6] = 120 - 30 * a[3]
    time[7] = 30 * a[4] + 90
    sum_1 = time[0] * a[0] + time[1] * a[1] + time[2] * a[1] + time[3] * a[2] + time[4] * a[2] + time[5] * a[3] + time[
        6] * a[3] + time[7] * a[4]
    sum_2 = a[0] + 2 * a[1] + 2 * a[2] + 2 * a[3] + a[4]
    result = sum_1 / sum_2
    return result

# 洗涤时间隶属度函数
def WashTime(a):  # a为时间值
    if 0 <= a <= 30:
        u1 = (30 - a) / 30
        u2 = a / 30
        if (u1 > u2):
            time_level = 'VS'
        else:
            time_level = 'S'
    if 30 < a <= 60:
        u3 = (60 - a) / 30
        u4 = (a - 30) / 30
        if (u3 > u4):
            time_level = 'S'
        else:
            time_level = 'M'
    if 60 < a <= 90:
        u5 = (90 - a) / 30
        u6 = (a - 60) / 30
        if (u5 > u6):
            time_level = 'M'
        else:
            time_level = 'L'
    if 90 < a <= 120:
        u7 = (120 - a) / 30
        u8 = (a - 90) / 30
        if (u7 > u8):
            time_level = 'L'
        else:
            time_level = 'VL'
    return time_level


# 定义视图来处理推理请求
@csrf_exempt
def fuzzy_inference(request):
    try:
        sludge_input = float(request.GET.get('sludge', 0))
        grease_input = float(request.GET.get('grease', 0))

        sludge_membership = Sludge(sludge_input)
        grease_membership = Grease(grease_input)
        rules_value = Rules(sludge_membership, grease_membership)
        time_level = Inference(rules_value)
        predicted_time = Max_membership(time_level)
        time_description = WashTime(predicted_time)

        flag = {'VS': '很短', 'S': '短', 'M': '中等', 'L': '长', 'VL': '很长'}
        response = {
            "time_sign": time_description,
            "time_description": flag[time_description],
            "predicted_time": predicted_time
        }
        return JsonResponse(response)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)

async def index(request):
    return await sync_to_async(render)(request, 'fuzzy_index.html')
